package com.chipcoo.mybatis.spring;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import static org.springframework.util.Assert.notNull;

public class MapperFactoryBean<T>  extends org.mybatis.spring.mapper.MapperFactoryBean<T> {
    public MapperFactoryBean() {}

    public MapperFactoryBean(Class<T> mapperInterface) {
        super(mapperInterface);
    }
    @Override
    protected void checkDaoConfig() {
        notNull(super.getSqlSession(), "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
        notNull(super.getMapperInterface(), "Property 'mapperInterface' is required");
        Configuration configuration = getSqlSession().getConfiguration();
        //LogUtils.debugInfo("do build111111111111111111",this);
        if (super.isAddToConfig() && !configuration.hasMapper(super.getMapperInterface())) {
            try {
                configuration.addMapper(super.getMapperInterface());


                Class<?>[] interfaces = super.getMapperInterface().getInterfaces();
                //LogUtils.debugInfo("do build22222222222222222222",this);
                if(null!=interfaces){
                    for(int i=0;i<interfaces.length;i++){

                        loadXmlResource(configuration,interfaces[i].getName());
                    }
                }
                if(super.getMapperInterface().getName().equals("com.xcode.yworld.dao.impl.SessionMapperImpl")){
                    for (Object object : new ArrayList<Object>(configuration.getMappedStatements())) {
                        if (object instanceof MappedStatement) {
                            MappedStatement ms = (MappedStatement) object;
                            //LogUtils.debugInfo(ms.getId(),this);
                        }
                    }

                }
            } catch (Exception e) {
                logger.error("Error while adding the mapper '" + super.getMapperInterface() + "' to configuration.", e);
                throw new IllegalArgumentException(e);
            } finally {
                ErrorContext.instance().reset();
            }
        }

    }
    private void loadXmlResource(Configuration configuration,String interfazeName) {
        // Spring may not know the real resource name so we check a flag
        // to prevent loading again a resource twice
        // this flag is set at XMLMapperBuilder#bindMapperForNamespace
        if (!configuration.isResourceLoaded("namespace:" + interfazeName)) {
            String xmlResource = interfazeName.replace('.', '/') + ".xml";
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream(super.getMapperInterface().getClassLoader(), xmlResource);
            } catch (IOException e) {
                // ignore, resource is not required
            }
            if (inputStream != null) {
                XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, configuration, xmlResource, configuration.getSqlFragments(), super.getMapperInterface().getName());
                xmlParser.parse();
            }
        }
    }
}